package com.zjuee.gateway;

import cn.hutool.core.util.IdUtil;
import com.zjuee.core.utils.RedisUtil;
import com.zjuee.gateway.utils.SecurityUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * shiro会话的持久化管理类，用于对会话信息的数据库操作
 *
 * @author wu liang
 * @since 2020/8/13 9:54
 */
public class MySessionDAO extends AbstractSessionDAO {
    private static final Logger logger = LoggerFactory.getLogger(MySessionDAO.class);
    public static final String PREFIX = "shiro_redis_session:";
    private RedisTemplate redisTpl;


    @Override
    public void update(Session session) throws UnknownSessionException {
        if (session==null || session.getId() == null){
            logger.error("redis update session error:session or session id is null");
            return;
        }

        try {
            redisTpl.opsForValue().set(RedisUtil.getPrefix() + PREFIX + session.getId().toString(), session, SecurityUtil.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new UnknownSessionException(e);
        }
    }

    @Override
    public void delete(Session session) {
        if (session==null || session.getId() == null){
            logger.error("redis delete session error:session or session id is null");
            return;
        }
        try {
            redisTpl.delete(RedisUtil.getPrefix() + PREFIX + session.getId().toString());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public Collection<Session> getActiveSessions() {
//        Set<Object> keys = RedisUtil.keys(PREFIX + "*");
        Set<Object> keys = null;
        Set<Session> sessions = new HashSet<Session>();
        if (keys != null && !keys.isEmpty()) {
            for (Object key : keys) {
                Session session=(Session) redisTpl.opsForValue().get(key);
                sessions.add(session);
            }
        }
        return sessions;
    }

    @Override
    protected Serializable doCreate(Session session) {
        if (session==null){
            logger.error("redis create session error:session is null");
            return null;
        }
        Serializable sessionId = IdUtil.fastSimpleUUID();
        assignSessionId(session, sessionId);
        redisTpl.opsForValue().set(RedisUtil.getPrefix() + PREFIX + sessionId.toString(), session, SecurityUtil.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if (sessionId == null){
            logger.error("redis read session error:sessionId is null");
            return null;
        }
        Session session = null;
        try {
            session = (Session) redisTpl.opsForValue().get(RedisUtil.getPrefix() + PREFIX + sessionId);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return session;
    }

    public void setRedisTpl(RedisTemplate redisTpl) {
        this.redisTpl = redisTpl;
    }
}
